/**
 * 人脸注册组件
 * 支持拍照和相册选择，进行人脸注册
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import React, { useState, useRef, useCallback } from 'react';
import { Button, Dialog, Toast, Space, Steps, Card } from 'antd-mobile';
// 移除图标导入，使用emoji图标
import { registerFace, detectFace, convertImageToBase64 } from '../../services/faceRecognitionService';
import { capturePhoto, getDeviceInfo } from '../../utils/cameraUtils';
import './index.module.css';

const FaceRegister = ({ 
  visible, 
  onClose, 
  onSuccess, 
  userId, 
  userInfo = '',
  qualityControl = 'NORMAL',
  livenessControl = 'NORMAL'
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [imageFile, setImageFile] = useState(null);
  const [imagePreview, setImagePreview] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [detectResult, setDetectResult] = useState(null);
  const fileInputRef = useRef(null);
  const cameraInputRef = useRef(null);

  // 步骤配置
  const steps = [
    { title: '选择照片', description: '拍照或从相册选择' },
    { title: '人脸检测', description: '检测人脸质量' },
    { title: '完成注册', description: '注册人脸信息' }
  ];

  // 重置状态
  const resetState = useCallback(() => {
    setCurrentStep(0);
    setImageFile(null);
    setImagePreview('');
    setIsProcessing(false);
    setDetectResult(null);
  }, []);

  // 关闭弹窗
  const handleClose = useCallback(() => {
    resetState();
    onClose();
  }, [resetState, onClose]);

  // 人脸检测
  const handleFaceDetection = useCallback(async (file) => {
    if (!file) return;

    setIsProcessing(true);
    
    try {
      // 转换图片为Base64
      const base64Image = await convertImageToBase64(file);
      
      // 进行人脸检测
      const result = await detectFace(base64Image);
      
      if (result.success) {
        const faceList = result.data.face_list;
        
        if (faceList && faceList.length > 0) {
          const face = faceList[0];
          setDetectResult(face);
          
          // 检查人脸质量
          const quality = face.quality;
          if (quality) {
            if (quality.occlusion?.left_eye > 0.6 || 
                quality.occlusion?.right_eye > 0.6 || 
                quality.occlusion?.nose > 0.7 || 
                quality.occlusion?.mouth > 0.7) {
              Toast.show('人脸被遮挡，请重新拍照');
              setCurrentStep(0);
              return;
            }
            
            if (quality.blur > 0.7) {
              Toast.show('图片模糊，请重新拍照');
              setCurrentStep(0);
              return;
            }
            
            if (quality.illumination < 20) {
              Toast.show('光线不足，请重新拍照');
              setCurrentStep(0);
              return;
            }
          }
          
          // 检查活体检测
          if (face.liveness && face.liveness.liveness < 0.8) {
            Toast.show('请确保是真人照片');
            setCurrentStep(0);
            return;
          }
          
          // 检测通过，进入注册步骤
          setCurrentStep(2);
        } else {
          Toast.show('未检测到人脸，请重新拍照');
          setCurrentStep(0);
        }
      } else {
        Toast.show(result.error || '人脸检测失败');
        setCurrentStep(0);
      }
    } catch (error) {
      console.error('人脸检测失败:', error);
      Toast.show('人脸检测失败，请重试');
      setCurrentStep(0);
    } finally {
      setIsProcessing(false);
    }
  }, []);

  // 处理文件选择
  const handleFileSelect = useCallback(async (file) => {
    if (!file) return;

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      Toast.show('请选择图片文件');
      return;
    }

    // 检查文件大小（限制10MB）
    if (file.size > 10 * 1024 * 1024) {
      Toast.show('图片大小不能超过10MB');
      return;
    }

    setImageFile(file);
    
    // 创建预览URL
    const previewUrl = URL.createObjectURL(file);
    setImagePreview(previewUrl);
    
    // 自动进入下一步
    setCurrentStep(1);
    
    // 开始人脸检测
    await handleFaceDetection(file);
  }, [handleFaceDetection]);

  // 拍照
  const handleTakePhoto = useCallback(async () => {
    try {
      const deviceInfo = getDeviceInfo();
      
      if (deviceInfo.isMobile) {
        // 移动端使用摄像头工具
        const file = await capturePhoto({
          capture: 'user', // 前置摄像头
          maxWidth: 1280,
          maxHeight: 720,
          quality: 0.8
        });
        
        await handleFileSelect(file);
      } else {
        // 桌面端使用文件输入
        cameraInputRef.current?.click();
      }
    } catch (error) {
      console.error('拍照失败:', error);
      Toast.show(error.message || '拍照失败，请重试');
    }
  }, [handleFileSelect]);

  // 选择相册
  const handleSelectFromAlbum = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  // 注册人脸
  const handleRegister = useCallback(async () => {
    if (!imageFile || !userId) return;

    setIsProcessing(true);
    
    try {
      // 转换图片为Base64
      const base64Image = await convertImageToBase64(imageFile);
      
      // 注册人脸
      const result = await registerFace(
        base64Image,
        userId,
        userInfo,
        {
          qualityControl,
          livenessControl,
          spoofingControl: 'NORMAL',
          actionType: 'APPEND'
        }
      );
      
      if (result.success) {
        Toast.show('人脸注册成功');
        onSuccess?.(result.data);
        handleClose();
      } else {
        Toast.show(result.error || '人脸注册失败');
      }
    } catch (error) {
      console.error('人脸注册失败:', error);
      Toast.show('人脸注册失败，请重试');
    } finally {
      setIsProcessing(false);
    }
  }, [imageFile, userId, userInfo, qualityControl, livenessControl, onSuccess, handleClose]);

  // 重新选择照片
  const handleReselect = useCallback(() => {
    setCurrentStep(0);
    setImageFile(null);
    setImagePreview('');
    setDetectResult(null);
  }, []);

  return (
    <Dialog
      visible={visible}
      onClose={handleClose}
      title="人脸注册"
      content={
        <div className="face-register">
          {/* 步骤指示器 */}
          <Steps current={currentStep} className="face-register-steps">
            {steps.map((step, index) => (
              <Steps.Step key={index} title={step.title} description={step.description} />
            ))}
          </Steps>

          {/* 步骤内容 */}
          <div className="face-register-content">
            {currentStep === 0 && (
              <div className="face-register-step">
                <div className="face-register-options">
                  <Card
                    className="face-register-option"
                    onClick={handleTakePhoto}
                  >
                    <div className="face-register-icon">📸</div>
                    <div className="face-register-text">拍照</div>
                  </Card>
                  
                  <Card
                    className="face-register-option"
                    onClick={handleSelectFromAlbum}
                  >
                    <div className="face-register-icon">📷</div>
                    <div className="face-register-text">相册</div>
                  </Card>
                </div>
                
                <div className="face-register-tips">
                  <h4>拍照要求：</h4>
                  <ul>
                    <li>请确保光线充足</li>
                    <li>人脸清晰，无遮挡</li>
                    <li>正面拍摄，表情自然</li>
                    <li>图片大小不超过10MB</li>
                  </ul>
                </div>
              </div>
            )}

            {currentStep === 1 && (
              <div className="face-register-step">
                {isProcessing ? (
                  <div className="face-register-processing">
                    <div className="face-register-spinner" />
                    <div>正在检测人脸...</div>
                  </div>
                ) : (
                  <div className="face-register-preview">
                    {imagePreview && (
                      <img 
                        src={imagePreview} 
                        alt="人脸预览" 
                        className="face-register-image"
                      />
                    )}
                    <div className="face-register-actions">
                      <Button onClick={handleReselect}>重新选择</Button>
                    </div>
                  </div>
                )}
              </div>
            )}

            {currentStep === 2 && (
              <div className="face-register-step">
                <div className="face-register-success">
                  <div className="face-register-success-icon">✓</div>
                  <h3>人脸检测通过</h3>
                  {detectResult && (
                    <div className="face-register-info">
                      <p>年龄：{detectResult.age}岁</p>
                      <p>性别：{detectResult.gender?.type === 'male' ? '男' : '女'}</p>
                      <p>表情：{detectResult.expression?.type === 'smile' ? '微笑' : '自然'}</p>
                    </div>
                  )}
                </div>
                
                <div className="face-register-actions">
                  <Space>
                    <Button onClick={handleReselect}>重新选择</Button>
                    <Button 
                      color="primary" 
                      loading={isProcessing}
                      onClick={handleRegister}
                    >
                      确认注册
                    </Button>
                  </Space>
                </div>
              </div>
            )}
          </div>
        </div>
      }
      actions={[
        {
          key: 'cancel',
          text: '取消',
          onClick: handleClose
        }
      ]}
    >
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        capture="environment"
        style={{ display: 'none' }}
        onChange={(e) => handleFileSelect(e.target.files[0])}
      />
      
      <input
        ref={cameraInputRef}
        type="file"
        accept="image/*"
        capture="user"
        style={{ display: 'none' }}
        onChange={(e) => handleFileSelect(e.target.files[0])}
      />
    </Dialog>
  );
};

export default FaceRegister;
